package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonQuestionBankBean;
import com.fancy.learncenter.bean.CartoonQuestionIdsBean;
import com.fancy.learncenter.bean.CartoonQuestionIdsItemBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.callback.OkOrCancelImpl;
import com.fancy.learncenter.ui.fragment.GrammarChooseFillBlankFragment;
import com.fancy.learncenter.ui.fragment.GrammarListenAndImageChooseTextFragment;
import com.fancy.learncenter.ui.fragment.GrammarListenChooseImageFragment;
import com.fancy.learncenter.ui.fragment.GrammarListenChooseTextFragment;
import com.fancy.learncenter.ui.fragment.GrammarSeeImageChooseFragment;
import com.fancy.learncenter.ui.fragment.SeeWordPuzzleFragment;
import com.fancy.learncenter.ui.fragment.WordFillBlankFragment;
import com.fancy.learncenter.ui.fragment.WordListenChooseImageFragment;
import com.fancy.learncenter.ui.fragment.WordSeeImageChooseWordFragment;
import com.fancy.learncenter.ui.fragment.WordSeeImageListenSpellFragment;
import com.fancy.learncenter.ui.view.CartoonDoWorkExitPopu;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.fancy.learncenter.common.JumpIntentKey.RIGHT_NUM;

/**
 * 作业题型
 */
public class CartoonQuestionTypeActivity extends BaseActivity implements
        GrammarSeeImageChooseFragment.OnSeeImageChooseListener,
        GrammarListenAndImageChooseTextFragment.OnListenChooseListener,
        WordListenChooseImageFragment.OnListenChooseImageListener,
        GrammarListenChooseTextFragment.OnListenChooseTextListener,
        WordFillBlankFragment.OnFillBlankListener,
        GrammarListenChooseImageFragment.OnGrammarListenChooseListener,
        WordSeeImageListenSpellFragment.OnWordSeeImageListenSpellListener,
        WordSeeImageChooseWordFragment.OnWordSeeImageChooseWordListener,
        GrammarChooseFillBlankFragment.OnGrammarChooseFillBlankListener,
        SeeWordPuzzleFragment.OnSeeWordPuzzleListener {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.current_index_text)
    TextView currentIndexText;
    @Bind(R.id.right_layout)
    LinearLayout rightLayout;
    @Bind(R.id.progress_num)
    TextView progressNum;
    @Bind(R.id.fg_container)
    FrameLayout fgContainer;
    int totalViewWidth;
    @Bind(R.id.progress_num_layout)
    FrameLayout progressNumLayout;
    @Bind(R.id.total_num_text)
    TextView totalNumText;
    int totalNum;
    ArrayList<QuestionVOsBean> questionBankList = new ArrayList<>();
    Fragment fragment;
    @Bind(R.id.title_text)
    TextView titleText;
    private JumpIntentKey.QUESTION_ENTER_TYPE type;
    private String homePackageId;
    private String studentHomeworkId;
    private String constructId;
    private Bundle bundle;
    private CartoonDoWorkExitPopu exitPopu;
    private int currentIndex;
    private String unitId;
    private String unitNameStr;
    private String lessonNameStr;
    Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCartoonContentView(R.layout.activity_question_type, Status.STATUS);
        ButterKnife.bind(this);
        getIntentData();
        initData();
    }


    private void getIntentData() {
        bundle = getIntent().getExtras();
        type = (JumpIntentKey.QUESTION_ENTER_TYPE) bundle.getSerializable(JumpIntentKey.QUESTION_ENTER);
        unitId = bundle.getString(JumpIntentKey.UNIT_ID);
        constructId = bundle.getString(JumpIntentKey.CONSTRUCTID);
    }

    private void getReceiveData() {
        questionBankList = bundle.getParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY);
        if (questionBankList != null) {
            totalNum = questionBankList.size();
        }

        getNormalData();
        lessonNameStr = bundle.getString(JumpIntentKey.LESSON_NAME);
        unitNameStr = bundle.getString(JumpIntentKey.UNIT_NAME);
        currentIndex = bundle.getInt(JumpIntentKey.CURRENT_INDEX, 0);
    }

    private void getNormalData() {
        homePackageId = bundle.getString(JumpIntentKey.HOMEWORK_PACKAGE_ID);
        studentHomeworkId = bundle.getString(JumpIntentKey.STUDENTHOMEWORKID);
    }

    private void initData() {

        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
                getReceiveData();
                initView();
                break;
            case DO_IT_AGAIN:
                getNormalData();
                getQuestionListData();
                break;
            case HAS_CORRECTED:
                getData(type);
                break;
            case NOT_CORRECTED:
                getData(type);
                break;
            case ERROR_KINDS:
                getErrorKindsByIdData();
                break;
            case WORK_REPORT:
                getReceiveData();
                initView();
                break;
        }

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type != null) {
                    switch (type) {
                        case DO_WORK:
                        case CONTINUE_WORK:
                            showExitPopu();
                            break;
                        default:
                            finish();
                            break;
                    }
                }

            }
        });

    }

    private void showExitPopu() {
        if (exitPopu == null) {
            exitPopu = new CartoonDoWorkExitPopu(this, back);
        }
        if (!exitPopu.isShowing()) {
            exitPopu.showPopupWindow();
        }

        exitPopu.setListener(new OkOrCancelImpl() {
            @Override
            public void ok() {
                RIGHT_NUM = 0;
                getRecordTime();
                finish();
            }

            @Override
            public void cancel() {

                exitPopu.dismiss();
            }
        });
    }

    /**
     * 获取开始时间,并将本次时间长度写入prefrerence中
     */
    private void getRecordTime() {

        long startTime = LoginUserSharePrefernce.getRecordStartTime(String.valueOf(homePackageId));
//        long startTime = 0;
//        if(!TextUtils.isEmpty(startTimeStr)){
//            startTime = Long.valueOf(startTimeStr);
//        }
        long endTime = System.currentTimeMillis();

        long timeDuration = endTime - startTime;
        long beforeTimeDuration = LoginUserSharePrefernce.getCartoonQuestionTime(homePackageId);
        LoginUserSharePrefernce.setCartoonQuestionTime(timeDuration + beforeTimeDuration, homePackageId);
        LoginUserSharePrefernce.setRecordStartTime(0, homePackageId);
    }


    private void getQuestionListData() {

        String fileName = Constant.CARTOON_QUESTION_BANK + String.valueOf(LoginUserSharePrefernce.getCustomId() + "_" + homePackageId) + ".td";
        if (!FileUtils.checKFileExists(Constant.CARTOON_QUESTION_BANK + fileName)) {

            downloadWork(fileName, studentHomeworkId);

        } else {
            String readResultStr = FileUtils.readFromSD(fileName);

            CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
            questionBankList.addAll(questionBankBean1.getQuestionVOs());

            if (questionBankList != null && questionBankList.size() > 0) {
                totalNum = questionBankList.size();
            }

            initView();
        }
    }

    /**
     * 下载作业包
     *
     * @param fileName
     * @param homeworkId
     */
    private void downloadWork(final String fileName, String homeworkId) {


        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkId", String.valueOf(homeworkId));
        HttpMehtod.getInstance().cartoonDownloadHomeWorkById(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonQuestionBankBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonQuestionBankBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonQuestionBankBean>() {
                    @Override
                    public void success(CartoonQuestionBankBean dataBean) {

                        String str = gson.toJson(dataBean);

                        FileUtils.creatFile(fileName);
                        FileUtils.saveStringToFile(fileName, str);
                        String readResultStr = FileUtils.readFromSD(fileName);
                        CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
                        questionBankList.addAll(questionBankBean1.getQuestionVOs());
                        if (questionBankList != null && questionBankList.size() > 0) {
                            totalNum = questionBankList.size();
                        }
                        initView();
                    }

                    @Override
                    public void fail(String errorCode) {
                        LogUtil.MyLog("fail", "=======11111=");
                    }
                }).dealData();
            }
        });
    }


    /**
     * 错题中心 根据id
     */
    private void getErrorKindsByIdData() {
        questionBankList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("constructId", constructId);
        map.put("unitId", unitId);
        map.put("classId", MyApplication.classIDStr);
        HttpMehtod.getInstance().cartoonListConstructId(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                dataUtils(responseBodyResponse);
            }
        });

    }

    private void dataUtils(Response<ResponseBody> responseBodyResponse) {
        BaseBean<CartoonQuestionIdsBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonQuestionIdsBean.class);

        CustomNetCallBack callBack = new CustomNetCallBack(this, baseBean);
        callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonQuestionIdsBean>() {
            @Override
            public void success(CartoonQuestionIdsBean dataBean) {


                List<CartoonQuestionIdsItemBean> idsItemBeanList = dataBean.getObjectQuestionIds();
                if (idsItemBeanList != null && idsItemBeanList.size() > 0) {
                    String fileName = Constant.CARTOON_QUESTION_BANK + String.valueOf(LoginUserSharePrefernce.getCustomId() + "_" + homePackageId) + ".td";
                    if (!FileUtils.checKFileExists(fileName)) {
                        downLoadHomeworkByQids(idsItemBeanList);
                    } else {

                        Gson gson = new Gson();
                        String readResultStr = FileUtils.readFromSD(fileName);
                        CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
                        ArrayList<QuestionVOsBean> tempQuestionArrayList = new ArrayList<>();
                        tempQuestionArrayList.addAll(questionBankBean1.getQuestionVOs());

                        for (CartoonQuestionIdsItemBean itemBean : idsItemBeanList) {
                            for (QuestionVOsBean vOsBean : tempQuestionArrayList) {
                                if (String.valueOf(vOsBean.getQuestionId()).equals(itemBean.getObjectQuestionId())) {
                                    questionBankList.add(vOsBean);
                                    break;
                                }
                            }
                        }
                        if (questionBankList.size() > 0) {
                            homePackageId = questionBankList.get(0).getHomeworkPackageId();
                            initView();
                        } else {
                            downLoadHomeworkByQids(idsItemBeanList);
                        }

                    }
                } else {
                    ToastUtil.show("  暂无错题");
                    finish();
                }

            }

            @Override
            public void fail(String errorCode) {

            }
        }).dealData();
    }


    /**
     * 获取已订正 未订正
     *
     * @param type
     */
    private void getData(JumpIntentKey.QUESTION_ENTER_TYPE type) {
        questionBankList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        map.put("unitId", unitId);
        switch (type) {
            case NOT_CORRECTED:

                map.put("correctState", 1);
                break;

            case HAS_CORRECTED:
                map.put("correctState", 2);
                break;
        }

        HttpMehtod.getInstance().cartoonCorrectState(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                dataUtils(responseBodyResponse);
            }
        });
    }


    /**
     * 根据拼接的ids获取列表
     *
     * @param list
     */
    private void downLoadHomeworkByQids(final List<CartoonQuestionIdsItemBean> list) {
        String ids = "";
        for (int i = 0; i < list.size(); i++) {
            if (i != list.size() - 1) {
                ids += list.get(i).getObjectQuestionId() + ",";
            } else {
                ids += list.get(i).getObjectQuestionId();
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("qids", ids);
        HttpMehtod.getInstance().cartoonDownLoadHomeworkByQids(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                BaseBean<CartoonQuestionBankBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonQuestionBankBean.class);

                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonQuestionBankBean>() {
                    @Override
                    public void success(CartoonQuestionBankBean dataBean) {

                        questionBankList = (ArrayList<QuestionVOsBean>) dataBean.getQuestionVOs();
                        if (questionBankList != null) {
                            totalNum = questionBankList.size();

                            for (CartoonQuestionIdsItemBean itemBean : list) {

                                for (QuestionVOsBean bean : questionBankList) {
                                    if (String.valueOf(bean.getQuestionId()).equals(itemBean.getObjectQuestionId())) {
                                        bean.setStudentHomeworkDoneDetailId(itemBean.getStudentHomeworkDoneDetailId());
                                        break;
                                    }
                                }
                            }
                            homePackageId = dataBean.getQuestionVOs().get(0).getHomeworkPackageId();
                            initView();
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();


            }
        });
    }


    @Override
    public void onBackPressed() {
        if (type != null) {
            switch (type) {
                case DO_WORK:
                case CONTINUE_WORK:
                    showExitPopu();
                    break;
                default:
                    super.onBackPressed();
                    break;
            }
        } else {
            super.onBackPressed();
        }
    }

    private void initView() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Utils.switchFragment(this, transaction, questionBankList, currentIndex, R.id.fg_container, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
    }

    @Override
    public void onSeeImageChoose(final int currentIndex, final int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);

    }

    private void notifyData(final int currentIndex, final int totalNum, String title) {
        progressNumLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            boolean isFirst = true;

            @Override
            public void onGlobalLayout() {

                if (isFirst) {
                    isFirst = false;
                    totalViewWidth = progressNumLayout.getMeasuredWidth();
                    int width = totalViewWidth * currentIndex / totalNum;
                    progressNum.setWidth(width);

                }
            }
        });
        currentIndexText.setText(String.valueOf(currentIndex) + "/");
        totalNumText.setText(String.valueOf(totalNum));
        titleText.setText(title);
    }


    @Override
    public void onListenChoose(final int currentIndex, final int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }

    @Override
    public void onListenChooseImage(final int currentIndex, final int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }

    @Override
    public void onListenChooseText(final int currentIndex, final int totalNum, String title) {

        notifyData(currentIndex, totalNum, title);
    }


    @Override
    public void onFillBlank(final int currentIndex, final int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }

    @Override
    public void onGrammarListenChoose(int currentIndex, int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }

    @Override
    public void onWordSeeImageListenSpell(int currentIndex, int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }

    @Override
    public void onWordSeeImageChooseWord(int currentIndex, int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }

    @Override
    public void onGrammarChooseFillBlank(int currentIndex, int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }

    @Override
    public void onSeeWordPuzzle(int currentIndex, int totalNum, String title) {
        notifyData(currentIndex, totalNum, title);
    }
}
